﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 登录命令
    /// </summary>
    public class LoginCommandHandler : IRequestHandler<LoginCommand, ApiResult<LoginDTO>>
    {
        private readonly IBaseRepository<User> userRep;

        public LoginCommandHandler(IBaseRepository<User> userRep)
        {
            this.userRep = userRep;
        }
        public async Task<ApiResult<LoginDTO>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<LoginDTO>();

            try
            {
                // 1. 验证输入
                if (string.IsNullOrWhiteSpace(request.Username) ||
                    string.IsNullOrWhiteSpace(request.Password))
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "用户名和密码不能为空";
                    result.Data = new LoginDTO
                    {
                        Success = false,
                        Message = "用户名和密码不能为空"
                    };
                    return result;
                }

                // 2. 查询用户
                var user = await userRep.GetAll()
                    .FirstOrDefaultAsync(u => u.Username == request.Username, cancellationToken);

                if (user == null)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "用户名或密码错误";
                    result.Data = new LoginDTO
                    {
                        Success = false,
                        Message = "用户名或密码错误"
                    };
                    return result;
                }

                // 3. 验证密码
                // 简单方案：直接比较（仅用于测试，生产环境必须加密）
                // 实际应使用：BCrypt.Net.BCrypt.Verify(request.Password, user.Password)
                bool isPasswordValid = request.Password == user.Password; // 仅示例，需要替换为加密验证

                if (!isPasswordValid)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "用户名或密码错误";
                    result.Data = new LoginDTO
                    {
                        Success = false,
                        Message = "用户名或密码错误"
                    };
                    return result;
                }

                // 4. 登录成功
                result.Code = ApiEnum.成功;
                result.Message = "登录成功";
                result.Data = new LoginDTO
                {
                    UserId = user.UserId,
                    Username = user.Username,
                    NickName = user.NickName,
                    Role = user.Role,
                    Success = true
                };

                return result;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"登录失败：{ex.Message}";
                result.Data = new LoginDTO
                {
                    Success = false,
                    Message = ex.Message
                };
                return result;
            }
        }
    }
}
